﻿@using Damselfly.Core.ScopedServices
@inherits LayoutComponentBase

@inject AuthenticationStateProvider authProvider
@inject IConfigService configService
@inject IUserMgmtService userService
@inject ILogger<MainLayout> logger
@inject ClientUIStateService uiStateService
@inject IDialogService dialogService
@inject IPeopleService peopleService

@implements IDisposable

<MudDialogProvider FullWidth="true" MaxWidth="MaxWidth.Small"/>
<MudPopoverProvider/>
<RadzenContextMenu/>
<UIStateMonitor/>

<DetailedErrorBoundary>
    <ChildContent>
        <CascadingAuthenticationState>
            <ThemeSwitcher>
                @if ( WaitingForAuth )
                {
                    <p>Checking Login Status...</p>
                }
                else
                {
                    @if ( ShowLogin )
                    {
                        <Login/>
                    }
                    else
                    {
                        <div class="damselfly-app">
                            @if ( uiStateService.IsSmallScreenDevice )
                            {
                                <MenuBar>
                                    <MenuContent>
                                        <SideBar/>
                                    </MenuContent>
                                </MenuBar>
                                @Body
                            }
                            else
                            {
                                <SplitView>
                                    <LeftPane>
                                        <SideBar/>
                                    </LeftPane>
                                    <RightPane>
                                        <div class="rightpane">
                                            @Body
                                        </div>
                                    </RightPane>
                                </SplitView>
                            }
                            <DetailedErrorBoundary>
                                <Statusbar/>
                            </DetailedErrorBoundary>
                        </div>
                    }
                }
            </ThemeSwitcher>
        </CascadingAuthenticationState>
    </ChildContent>
    <ErrorContent>
        <p>An error occurred. Please check the Damselfly logs and reload the page.</p>
    </ErrorContent>
</DetailedErrorBoundary>

@code
{
    bool ShowLogin = false;
    bool WaitingForAuth = false;

    private async void AuthStateChanged(Task<AuthenticationState> authStateTask)
    {
        var authState = await authStateTask;

        if( authState != null )
        {
            ShowLogin = ! authState.User.Identity.IsAuthenticated;

            StateHasChanged();
        }
    }

    private async Task CheckForAIMigration()
    {
        if( await peopleService.NeedsAIMigration() )
        {
            var parameters = new DialogParameters();
            var options = new MudBlazor.DialogOptions { MaxWidth = MaxWidth.Small, BackdropClick = false };
            var dialog = dialogService.Show<AIMigrationDialog>("AI Migration", parameters, options);
            var result = await dialog.Result;
        }
    }

    public void Dispose()
    {
        authProvider.AuthenticationStateChanged -= AuthStateChanged;
        uiStateService.OnStateChanged -= UIStateChanged;
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if ( firstRender )
        {
            try
            {
                uiStateService.OnStateChanged += UIStateChanged;
                await CheckForAIMigration();
            }
            catch( Exception ex )
            {
                logger.LogWarning("Unable to execute getInnerWidth to establish if running on Mobile");
            }
        }
    }

    private void UIStateChanged( UIClientState state )
    {
        StateHasChanged();
    }

    protected override async Task OnInitializedAsync()
    {
        authProvider.AuthenticationStateChanged += AuthStateChanged;

        var forceLogin = configService.GetBool(ConfigSettings.ForceLogin);

        if ( forceLogin )
        {
            WaitingForAuth = true;

            var authState = await authProvider.GetAuthenticationStateAsync();

            var user = authState.User;

            if ( !user.Identity.IsAuthenticated )
            {
                // Check if any users have been created. If there aren't any, then we need to allow
                // the user to create the first one, so disable the login redirect.
                var users = await userService.GetUsers();

                if ( users.Any() )
                {
                    ShowLogin = true;
                }
            }

            WaitingForAuth = false;
        }
    }
}